package com.limetalks.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.mail.MessagingException;
import javax.persistence.Persistence;
import javax.persistence.PersistenceException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.limetalks.dao.UserDAO;
import com.limetalks.data.User;
import com.limetalks.util.DAO;
import com.limetalks.util.GlobalStrings;
import com.limetalks.util.Helper;
import com.limetalks.util.MailSender;


public class RegisterServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
    
	private UserDAO userDAO;
	
    public RegisterServlet() {
        super();
        userDAO = new UserDAO(Persistence.createEntityManagerFactory(GlobalStrings.PERSISTENCE_UNIT_NAME));
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String code = request.getParameter("code");
		if(code == null || code.trim().equals("")) {
			
			String email = request.getParameter("email");
			String login = request.getParameter("login");
			String password = request.getParameter("password");
			
			//TODO: check email, login already used
			
			// generate random string for confirming via email
			//String randStr = Helper.randomString();
			
			// create new user record in database
			//new DAO().addUser(email, login, password, randStr);
			
			String status = "success";
			
			User user = new User();
			user.setEmail(email);
			user.setPassword(password);
			user.setName(login);
			
			try {
				userDAO.save(user);
			} catch (PersistenceException e) {
				status = "error";
				//e.printStackTrace();
			} finally {
				response.sendRedirect("register.jsp?status="+status);
			}
			
			// send email with string
			/*try {
				new MailSender().sendRegEmail(email, randStr);
			} catch (MessagingException e) {
				response.sendRedirect("register.jsp?status=error");
			}*/
			
			
		
		} else { // registration confirmation
			
			//TODO: check code in db and confirm registration
			//new DAO().confirmReg(code);
			response.sendRedirect("register.jsp?status=confirm");
		}
	}
}
